//
//
///

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {Image, DeviceEventEmitter, RefreshControl, ListView, StyleSheet, Text, View} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import ViewUtils from "../../../utils/ViewUtils";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import Navigation from "../../../custom/Navigation";
import LoginPage from "../LoginPage";
import I18n from "../../../res/language/i18n";
import ModalListUtils from "../../../utils/ModalListUtils";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import IparInput from "../../../custom/IparInput";

export default class ActivateTowPage extends Component {


    constructor(props) {
        super(props);

        this.countryData = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2,
        }).cloneWithRows(this.props.countryData || []);

        this.iparNetwork = new IparNetwork();

        this.userMobile = '';
        this.userPassword = '';
        this.verificationCodeText = '';


        this.state = {
            loading: false,
            modalVisible: false,
            selectedIndex: -1,
            areaCode: I18n.t('default.countryCode'),
            verificationTimer: I18n.t('default.sendVerCode'),

        }

    }


    submit() {

        if (this.state.areaCode === I18n.t('default.countryCode')) {
            DeviceEventEmitter.emit('toast', I18n.t('default.countryCode'));
            return
        }

        if (!this.userMobile.trim()) {
            DeviceEventEmitter.emit('toast', I18n.t('default.enterPhoneNum'));
            return
        }
        if (!this.verificationCodeText.trim()) {
            DeviceEventEmitter.emit('toast', I18n.t('toast.enterVerification'));
            return
        }
        if (!this.userPassword.trim()) {
            DeviceEventEmitter.emit('toast', I18n.t('default.enterPass'));
            return
        }

        if (!CommonUtils.isPassword(this.userPassword)) {
            DeviceEventEmitter.emit('toast', I18n.t('toast.isNotPassword'));
            return;
        }

        this.setState({
            loading: true,
        });

        let user_data = this.props.userNewInfo;

        let formData = new FormData();
        formData.append('user_id', user_data.userData && user_data.userData.main_user_id);
        formData.append('area_code', this.props.countryData[this.state.selectedIndex].area_code);
        formData.append('mobile', this.userMobile);
        formData.append('code', this.verificationCodeText);
        formData.append('nick_name', user_data.nickName);
        formData.append('id_number', user_data.id_number);
        formData.append('personal_tax', user_data.personal_tax);
        formData.append('birth_day', user_data.birth_day);
        formData.append('id_img', user_data.passportImage);
        formData.append('user_pass', this.userPassword);


        this.iparNetwork.getPostFrom(SERVER_TYPE.admin + 'activeUserInfo', formData)
            .then((result) => {
                this.setState({
                    loading: false,
                });
                if (result.code === 200) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    if (this.props.comeFromMePage) {
                        this.props.navigator.popToTop();
                        DeviceEventEmitter.emit('loadUserData');
                    } else {
                        new CommonUtils().popToRoute(this, 'LoginPage');
                    }
                } else if (result.code === 444) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.verCodeError'))
                } else {
                    console.log(result);
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                }
            })
            .catch((error) => {
                this.setState({
                    loading: false,
                });
                console.log('ActivateTowPage---submit--error: ', error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })

    }


    /**
     * 点击各个国家的区号
     * */
    onModalItemClick(index, text) {
        this.setState({
            areaCode: text,
            selectedIndex: index,
            modalVisible: false,
        })
    }

    /**
     * finish page的时候
     */
    componentWillUnmount() {
        this._timer && clearInterval(this._timer);

        this.countryData = null;
        this.iparNetwork = null;
        this.userMobile = null;
        this.userPassword = null;
        this.verificationCodeText = null;

    }

    /**
     * 点击获取验证码
     * */
    verificationCode() {
        if (this.state.areaCode === I18n.t('default.countryCode')) {
            DeviceEventEmitter.emit('toast', I18n.t('default.countryCode'));
            return
        }

        if (!this.userMobile.trim()) {
            DeviceEventEmitter.emit('toast', I18n.t('default.enterPhoneNum'));
            return
        }


        if (this.props.userNewInfo.userData.mobile === this.userMobile) {
            this.sendVerificationCode()
        } else {
            this.checkMobile()
        }

    }


    checkMobile() {
        this.setState({
            loading: true,
        });
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'checkUserKey?', 'keywords=' + this.userMobile)
            .then((result) => {
                if (result.code === 200) {//用户已存在
                    this.setState({
                        loading: false,
                    });
                    DeviceEventEmitter.emit('toast', I18n.t('default.userHasAlready'))
                } else {//用户未存在
                    this.sendVerificationCode()
                }
            })
            .catch((error) => {
                this.setState({
                    loading: false,
                });
                console.log(error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
            });
    }


    /**
     * 发送验证码
     */
    sendVerificationCode() {
        this.stopTime();
        this.setState({
            loading: true,
        });
        let countryDatum = this.props.countryData[this.state.selectedIndex];


        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'sms?',
            'phone=' + this.userMobile + '&type=activate&country=' + countryDatum.area_code)
            .then((result) => {

                if (result.code === 200) {
                    this.countTime();
                    DeviceEventEmitter.emit('toast', I18n.t('toast.sendVerCodeSuccess'));
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }

                this.setState({
                    loading: false,
                });
            })
            .catch((error) => {
                this.setState({
                    loading: false,
                });
                console.log(error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            });

    }

    /**
     * 发送验证码的效果（btn 的 文字（59...））
     */
    countTime() {
        this._index = 60;
        this._timer = setInterval(() => {
            this.setState({verificationTimer: this._index-- + ' s'});
            if (this.state.verificationTimer <= 0 + ' s') {
                this._timer && clearInterval(this._timer);
                this.setState({verificationTimer: I18n.t('toast.againGetCode')});
            }
        }, 1000);
    }

    stopTime() {
        this._timer && clearInterval(this._timer);
        this.setState({verificationTimer: I18n.t('toast.againGetCode') + "..."});
    }

    render() {
        return (

            <View style={StyleUtils.flex}>

                <Navigation
                    onClickLeftBtn={() => this.props.navigator.pop()}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                />
                <KeyboardAwareScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.loading}
                            onRefresh={() => {
                            }}
                        />
                    }>
                    <View style={{padding: 16}}>
                        {/*title*/}
                        {ViewUtils.getTitleView('Register', 'personal information')}

                        <View style={[StyleUtils.justifySpace]}>
                            {ViewUtils.getButtunMenu(this.state.areaCode, () => this.setState({modalVisible: true}), [StyleUtils.marginTop, {width: '33%'}])}

                            <IparInput
                                style={{width: '64%'}}
                                onChangeText={(text) => this.userMobile = text}
                                placeholder={I18n.t('default.enterPhoneNum')}/>

                        </View>

                        <View style={[StyleUtils.center, StyleUtils.justifySpace, StyleUtils.marginTop]}>

                            <IparInput
                                keyboardType={'number-pad'}
                                style={{
                                    marginTop: 0,
                                    width: '64%'
                                }}
                                onChangeText={(text) => this.verificationCodeText = text}
                                placeholder={I18n.t('toast.enterVerification')}/>

                            {ViewUtils.getButton(this.state.verificationTimer, () => this.verificationCode(), {width: '33%'}, {fontSize: 14})}

                        </View>

                        <IparInput
                            isPassword={true}
                            onChangeText={(text) => this.userPassword = text}
                            placeholder={I18n.t('default.enterPass')}/>


                        {ViewUtils.getButton('NEX', () => this.submit(), [{marginBottom: 40}, StyleUtils.marginTop])}
                    </View>
                </KeyboardAwareScrollView>


                <ModalListUtils
                    dataParam={'area_code'}
                    visible={this.state.modalVisible}
                    dataSource={this.countryData}
                    onPress={(index, text) => this.onModalItemClick(index, text)}
                />


            </View>

        );
    }
}




